package com.scm.biz.action;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.scm.biz.bean.DesignOrder;
import com.scm.biz.bean.Order;
import com.scm.biz.bean.SysRole;
import com.scm.biz.dto.ProofingOrderDto;
import com.scm.biz.dto.ProofingOrderNotice;
import com.scm.biz.dto.ProofingPatternDto;
import com.scm.biz.dto.SampleStoreDto;
import com.scm.biz.query.FactoryQuery;
import com.scm.biz.query.ProofingOrderQuery;
import com.scm.biz.query.SampleStoreQuery;
import com.scm.biz.result.DesignOrderResult;
import com.scm.biz.result.ProofingOrderResult;
import com.scm.biz.result.SampleStoreResult;
import com.scm.biz.service.BusinessFileService;
import com.scm.biz.service.CustomerService;
import com.scm.biz.service.DesignOrderService;
import com.scm.biz.service.FactoryService;
import com.scm.biz.service.OrderPatternService;
import com.scm.biz.service.OrderService;
import com.scm.biz.service.ProofingOrderService;
import com.scm.biz.service.ProofingPatternService;
import com.scm.biz.service.ProofingPatternSizeService;
import com.scm.biz.service.SampleStoreService;
import com.scm.biz.service.SysUserService;
import com.scm.core.bean.exp.UfdmException;
import com.scm.core.bean.resp.RespBean;
import com.scm.utils.Const;
import com.scm.utils.UploadAndDownUtil;

import net.sf.json.JSONArray;

/**
 * 打样订单的action类
 * @author Young
 * @Date 2016.11.22
 */
@Controller
@RequestMapping("/proofingorder")
public class ProofingOrderAction {
	
	@Resource
	private ProofingOrderService proofingOrderService;
	@Resource
	private CustomerService customerService;
	@Resource
	private OrderPatternService orderPatternService;
	@Resource
	private ProofingPatternSizeService proofingPatternSizeService;
	@Resource
	private FactoryService factoryService;
	@Resource
	private ProofingPatternService proofingPatternService;
	@Resource
	private SampleStoreService sampleStoreService;
	@Resource
	BusinessFileService businessFileService;
	@Resource
	DesignOrderService designOrderService;
	@Resource
	OrderService orderService;
	@Resource
	private SysUserService sysUserService;
	/**
	 * 展示打样订单列表
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView doProofingOrderList(ProofingOrderQuery proofingOrderQuery,HttpServletRequest req){
		if(proofingOrderQuery.getPageNo() == 0){
			proofingOrderQuery.setPageNo(1);
		}
		Integer userId = Integer.valueOf(SecurityUtils.getSubject().getSession().getAttribute("userId").toString());
		proofingOrderQuery.setPerformer(userId);
		List<SysRole> sysRoleList = (List<SysRole>)SecurityUtils.getSubject().getSession().getAttribute("_roleList");
		//判断是否为设计总监或者供应链总监
		for(SysRole sysRole:sysRoleList){
			if(sysRole.getCode().equals("R007") || sysRole.getCode().equals("R001")){
				proofingOrderQuery.setIsOpen(1);
				break;
			}
		}
		List<ProofingOrderResult> list=proofingOrderService.selectByPage(proofingOrderQuery);
		//设置打样订单总数
		proofingOrderQuery.setRecourdCount(proofingOrderService.selectTotal(proofingOrderQuery));
		ModelAndView mav=new ModelAndView("order/proofingOrder_list");
		mav.addObject("customerName",proofingOrderQuery.getCustomerName());
		mav.addObject("code", proofingOrderQuery.getCode());
		mav.addObject("status",proofingOrderQuery.getStatus());
		mav.addObject("factoryList",factoryService.selectList(new FactoryQuery()));
		mav.addObject("proofingOrders",list);
		mav.addObject("managerList", sysUserService.selectListByRoleCode("R003"));//项目经理
		mav.addObject("splitPage", proofingOrderQuery.getSplitPage());
		mav.addObject("url", Const.getPath(req));
		return mav;
	}
	@RequestMapping("/detail")
	public ModelAndView detail(Long proofingPatternId){
		ProofingOrderResult proofingOrderResult=proofingOrderService.selectById(proofingPatternId);
		
		ModelAndView mav=new ModelAndView("order/proofingOrder_detail");
		mav.addObject("factoryList",factoryService.selectList(new FactoryQuery()));
		mav.addObject("proofingOrderResult",proofingOrderResult);
		return mav;
	}
	/**
	 * 跳转到新增打样订单页面
	 * @return
	 */
	@RequestMapping("/add")
	public ModelAndView doShowProofingOrderAddPage(Long orderId){
		ModelAndView mvAndView = new ModelAndView("order/proofingOrder_add");
		
		DesignOrder designOrder = designOrderService.selectByOrderId(orderId);
		DesignOrderResult designOrderResult = designOrderService.selectById(designOrder.getId());
		mvAndView.addObject("orderId",orderId);
		mvAndView.addObject("designOrderResult",designOrderResult);
		
		mvAndView.addObject("orderPatterList",orderPatternService.selectListByOrderId(orderId));
		return mvAndView;
	}
	
	/**
	 * 保存打样订单
	 * @param proofingOrder
	 * @return
	 * @throws UfdmException 
	 */
	@RequestMapping("/doCreateProofingOrder")
	@ResponseBody
	public RespBean<String> doCreateProofingOrder(ProofingOrderDto proofingOrderDto) throws UfdmException{
		RespBean<String> respBean=new RespBean<String>();
		Order order = orderService.selectById(proofingOrderDto.getOrderId());
		
		if(order.getManager() == null){
			throw new UfdmException("该订单项目经理为空不能创建打样订单,请先指派项目经理");
		}
		if(proofingOrderDto.getProofingEnddate()==null || proofingOrderDto.getProofingEnddate().isEmpty()){
			throw new UfdmException("打样截至日期不能为空");
		}
		if(proofingOrderDto.getPatternSizeList() ==null){
			throw new UfdmException("打样款型总数不能为0");
		}
		proofingOrderService.insert(proofingOrderDto);
	
		return respBean;
	}
	
	/**
	 * 选样或者客户来样创建打样订单
	 * @param proofingOrderDto
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/doSave")
	@ResponseBody
	public RespBean<Long> doSave(ProofingOrderDto proofingOrderDto,HttpServletRequest req) throws Exception{
		RespBean<Long> respBean=new RespBean<Long>();
		if("0".equals(req.getParameter("count"))){
			throw new UfdmException("打样款型总数不能为0");
		}
		Long id=proofingOrderService.save(proofingOrderDto,req);
		respBean.setBody(id);
		return respBean;
	}
	
	
	/**
	 * 选择样衣之后，跳转到创建打样订单页面
	 * @param custoerId 客户ID
	 * @param ids  多个样衣ID拼接字符串
	 * @return
	 */
	@RequestMapping("/addPage")
	public ModelAndView doShowAddPage(Long customerId,String customerName,String ids){
		ModelAndView mv=new ModelAndView("order/proofingOrder_add2");
		mv.addObject("customerList",customerService.selectList());
		String[] id;
		if(ids==null||ids.trim().isEmpty()){
			id=new String[]{};
		}else{
			id=ids.split(Const.SPLIT);
		}
		List<SampleStoreResult> list=new ArrayList<>();
		list=sampleStoreService.selectListByIds(id);
		mv.addObject("sampleStoreList", list);
		mv.addObject("customerId", customerId);
		mv.addObject("customerName", customerName);
		mv.addObject("managers", sysUserService.getManager());
		mv.addObject("ids", ids);
		return mv;
	}
	
	/**
	 * 添加客户提供样衣页面
	 * @return
	 */
	@RequestMapping("/addSample")
	public ModelAndView doAddSampleStore(Long customerId,String customerName,String ids){
		ModelAndView mv=new ModelAndView("order/proofingOrder_customer");
		String[] id;
		if(ids!=null&&!ids.trim().isEmpty()){
			id=ids.split(Const.SPLIT);
		}else{
			id=new String[]{};
		}
		List<SampleStoreResult> list=sampleStoreService.selectListByIds(id);
		mv.addObject("sampleStoreList", list);
		if(customerId==null) mv.addObject("customerList",customerService.selectList());
		mv.addObject("customerId", customerId);
		mv.addObject("customerName", customerName);
		mv.addObject("ids", ids);
		return mv;
	}
	
	/**
	 * 选择样衣页面
	 * @param query
	 * @return
	 */
	@RequestMapping("/selectSample")
	public ModelAndView doSelectSampleStore(SampleStoreQuery query,HttpServletRequest req){
		ModelAndView mv=new ModelAndView("order/sampleStore_choose");
		if(query.getPageNo()==null||query.getPageNo()==0){
			query.setPageNo(1);
		}
		List<SampleStoreDto> list=sampleStoreService.getList(query);
		mv.addObject("sampleStoreList", list);
		mv.addObject("ids", req.getParameter("ids"));
		mv.addObject("customerId",req.getParameter("customerId"));
		mv.addObject("customerName",req.getParameter("customerName"));
		mv.addObject("splitPage", query.getSplitPage());
		mv.addObject("query",query);
		mv.addObject("path", Const.getPath(req));
		return mv;
	}
	@RequestMapping("/saveClose")
	@ResponseBody
	public RespBean<String> saveClose(Long proofingPatternId,Long proofingOrderId){	
		proofingOrderService.saveClose(proofingOrderId);
		RespBean<String> respBean = new RespBean<String>();
		return respBean;
	}
	/**
	 * 创建打样订单成功
	 * @return
	 */
	@RequestMapping("/success")
	public ModelAndView doAddSuccess(Long id){
		ModelAndView mv=new ModelAndView("order/proofingOrder_success");
		mv.addObject("id",id);
		return mv;
	}
	
	/**
	 * 生成打样生成通知单成功
	 * @return
	 */
	@RequestMapping("/generateSuccess")
	public ModelAndView generateSuccess(Long id,String ids){
		ModelAndView mv=new ModelAndView("order/proofingOrder_info_success");
		mv.addObject("id",id);
		mv.addObject("ids",ids);
		return mv;
	}
	
	/**
	 * 填写打样生产通知单
	 */
	@RequestMapping("/fillNotice")
	public ModelAndView fillNotice(String ids,Integer index,Long proofingOrderId){
		ModelAndView mv=new ModelAndView("order/proofingOrder_notice");
		String[] id;
		if(index==null){
			if(ids!=null){
				id=ids.split(Const.SPLIT);
			}else{
				id=new String[]{};
			}
		}else{
			id=new String[]{ids.split(Const.SPLIT)[index]};
		}
		List<ProofingPatternDto> list=proofingPatternService.getByIds(id);
		mv.addObject("proofingPatterns", list);
		mv.addObject("index", index);
		mv.addObject("ids", ids);
		mv.addObject("proofingOrderId", proofingOrderId);
		mv.addObject("factoryList", factoryService.selectList(null));
		return mv;
	}
	
	/**
	 * 生成打样通知单预览
	 * @return
	 */
	@RequestMapping("/generateView")
	public ModelAndView generateView(String ids,Integer index){
		ModelAndView mv=new ModelAndView("order/proofingOrder_info_view");
		String[] id=ids.split(Const.SPLIT);
		ProofingOrderNotice proofingOrder=proofingOrderService.getByProofingPatternId(new Long(id[0]));
		List<ProofingPatternDto> list=proofingPatternService.getByIds(id);
		mv.addObject("proofingOrder",proofingOrder);
		mv.addObject("proofingPatterns", list);
		mv.addObject("ids", ids);
		mv.addObject("index", index);
		return mv;
	}
	
	/**
	 * 打样通知单修改
	 * @param req
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public RespBean<String> doEdit(HttpServletRequest req) throws Exception{
		RespBean<String> respBean=new RespBean<String>();
		String proofings=req.getParameter("proofings");
		JSONArray arr=JSONArray.fromObject(proofings);
		for(int i=0;i<arr.size();i++){
			int count=arr.getJSONObject(i).getInt("count");
			if(count==0){
				respBean.setBody("第"+(i+1)+"款样衣打样数量为零");
				return respBean;
			}
		}
		proofingOrderService.update(req,arr);

		return respBean;
	}
	
	/**
	 * 产生PDF文件
	 * @param request
	 * @param response
	 * @return
	 * @throws UfdmException 
	 * @throws Exception 
	 */
	@RequestMapping("/exportPdf")
	@ResponseBody
	public RespBean<String> expoprtPdf(MultipartHttpServletRequest request, HttpServletResponse response) throws UfdmException{
		UploadAndDownUtil.expoprtPdf("/pdf/dy_", request, response);
		RespBean<String> respBean=new RespBean<String>();
		return respBean;
	}
	
	/**
	 * 下载打样通知单
	 * @param id
	 * @param req
	 * @param res
	 * @throws UfdmException
	 */
	@RequestMapping("/downPdf")
	public void DownPdf(String id,HttpServletRequest req, HttpServletResponse res) throws UfdmException{
		UploadAndDownUtil.downFile("打样通知单_"+id+".pdf", "/pdf/dy_"+id+".pdf", req, res);
	}
}
